<?php

namespace App\Traits;

use Illuminate\Support\Facades\Log;
use PhpOffice\PhpSpreadsheet\IOFactory;

/**
 * excel 文件读取 Trait
 *
 * @author WangBin
 * @date 2021/8/20
 */
trait ExcelReader
{
    /**
     * 读取 excel 文件内容
     *
     * @param string $filePath
     * @param int $sheetNo
     * @return array
     * @author WangBin
     * @date 2021/8/20
     */
    public function read(string $filePath, int $sheetNo = null)
    {
        $data = []; // excel 表数据
        try {
            $fileReader = IOFactory::createReader('Xlsx');
            if(!$fileReader->canRead($filePath)) {
                $fileReader = IOFactory::createReader('Xls');
                if(!$fileReader->canRead($filePath)) {
                    throw new \Exception($filePath);
                }
            }
            $excel = $fileReader->load($filePath);
            $sheet = $excel->getActiveSheet();
            // 遍历行数据
            foreach ($sheet->getRowIterator(2) as $row) {
                // 行数据
                $item = [];
                // 遍历列数据
                foreach ($row->getCellIterator() as $cell) {
                    $item[$cell->getColumn()] = trim($cell->getValue());
                }
                $data[] = $item;
            }
        } catch (\Exception $exception) {
            $data = [];
            Log::debug("[excel 导入] 读取 excel 失败：{$exception->getMessage()}");
        }
        return $data;
    }
}